﻿namespace KeRui.BLL
{
    using KeRui.Common;
    using KeRui.Model;
    using KeRui.TemplateMaker;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Text;
    using System.Text.RegularExpressions;

    public class CmsContentInterface
    {
        private DataTable dtResutlData = new DataTable("CmsContent");

        private DataTable Catch(int nodeID, string catchContent)
        {
            Exception exception;
            KeRui.BLL.CmsField field = new KeRui.BLL.CmsField();
            KeRui.BLL.CmsNode node = new KeRui.BLL.CmsNode();
            List<KeRui.Model.CmsField> listByCache = field.GetListByCache("ModelID=" + node.GetModelByCache(nodeID).ModelID + " AND IsUsing='True'");
            DataColumn column = new DataColumn("NodeID", typeof(int));
            this.dtResutlData.Columns.Add(column);
            DataColumn column2 = new DataColumn("PublicState", typeof(int));
            this.dtResutlData.Columns.Add(column2);
            DataColumn column3 = new DataColumn("ContentState", typeof(int));
            this.dtResutlData.Columns.Add(column3);
            DataColumn column4 = new DataColumn("ContentType", typeof(int));
            this.dtResutlData.Columns.Add(column4);
            DataColumn column5 = new DataColumn("PublishTime", typeof(string));
            this.dtResutlData.Columns.Add(column5);
            DataColumn column6 = new DataColumn("IsRecommend", typeof(int));
            this.dtResutlData.Columns.Add(column6);
            DataColumn column7 = new DataColumn("IsHot", typeof(int));
            this.dtResutlData.Columns.Add(column7);
            DataColumn column8 = new DataColumn("IsMarked", typeof(int));
            this.dtResutlData.Columns.Add(column8);
            DataColumn column9 = new DataColumn("IsTop", typeof(int));
            this.dtResutlData.Columns.Add(column9);
            foreach (KeRui.Model.CmsField field2 in listByCache)
            {
                DataColumn column10 = new DataColumn(field2.FieldName, GetFieldType(field2.FieldType));
                this.dtResutlData.Columns.Add(column10);
            }
            MatchCollection matchs = Regex.Matches(catchContent, @"&(\w+)=.*?", RegexOptions.RightToLeft);
            DataRow row = this.dtResutlData.NewRow();
            row["NodeID"] = nodeID;
            Regex regex = new Regex(@"publicstate=(?<publicstate>\w+)", RegexOptions.IgnoreCase);
            string strValue = regex.Match(catchContent).Groups["publicstate"].ToString();
            row["PublicState"] = (strValue == "") ? 0 : Utils.StrToInt(strValue, 0);
            Regex regex2 = new Regex(@"contentstate=(?<contentstate>\w+)", RegexOptions.IgnoreCase);
            string str2 = regex2.Match(catchContent).Groups["contentstate"].ToString();
            row["ContentState"] = (str2 == "") ? 0 : Utils.StrToInt(str2, 0);
            Regex regex3 = new Regex(@"contentstate=(?<contenttype>\w+)", RegexOptions.IgnoreCase);
            string str3 = regex2.Match(catchContent).Groups["contenttype"].ToString();
            row["ContentType"] = (str3 == "") ? 0 : Utils.StrToInt(str3, 0);
            Regex regex4 = new Regex("publishtime=(?<publishtime>.*?)&", RegexOptions.IgnoreCase);
            string s = Utils.UrlDecode(regex4.Match(catchContent).Groups["publishtime"].ToString());
            try
            {
                DateTime time = DateTime.Parse(s);
            }
            catch (Exception exception1)
            {
                exception = exception1;
                s = DateTime.Now.ToString();
            }
            row["PublishTime"] = s;
            Regex regex5 = new Regex(@"contentid=(?<contentid>\w+)", RegexOptions.IgnoreCase);
            string str5 = regex5.Match(catchContent).Groups["contentid"].ToString();
            row["ContentID"] = (str5 == "") ? 0 : Utils.StrToInt(str5, 0);
            Regex regex6 = new Regex(@"isrecommend=(?<isrecommend>\w+)", RegexOptions.IgnoreCase);
            string str6 = regex6.Match(catchContent).Groups["isrecommend"].ToString();
            row["IsRecommend"] = (str6 == "") ? 0 : Utils.StrToInt(str6, 0);
            Regex regex7 = new Regex(@"ishot=(?<ishot>\w+)", RegexOptions.IgnoreCase);
            string str7 = regex7.Match(catchContent).Groups["ishot"].ToString();
            row["IsHot"] = (str7 == "") ? 0 : Utils.StrToInt(str7, 0);
            Regex regex8 = new Regex(@"ismarked=(?<ismarked>\w+)", RegexOptions.IgnoreCase);
            string str8 = regex8.Match(catchContent).Groups["ismarked"].ToString();
            row["IsMarked"] = (str8 == "") ? 0 : Utils.StrToInt(str8, 0);
            Regex regex9 = new Regex(@"istop=(?<istop>\w+)", RegexOptions.IgnoreCase);
            string str9 = regex9.Match(catchContent).Groups["istop"].ToString();
            row["IsTop"] = (str9 == "") ? 0 : Utils.StrToInt(str9, 0);
            for (int i = 0; i < matchs.Count; i++)
            {
                Regex regex10 = new Regex("[&]?(?<fieldname>.+)=(?<fieldvalue>.*)", RegexOptions.IgnoreCase);
                foreach (KeRui.Model.CmsField field2 in listByCache)
                {
                    if (field2.FieldName.ToLower() == regex10.Match(matchs[i].ToString()).Groups["fieldname"].ToString())
                    {
                        row[field2.FieldName] = Utils.UrlDecode(regex10.Match(matchs[i].ToString()).Groups["fieldvalue"].ToString(), "utf-8");
                        if (GetFieldType(field2.FieldType) == typeof(string))
                        {
                            if (field2.FieldType == 1)
                            {
                                row[field2.FieldName] = Utils.cutTrueLength(row[field2.FieldName].ToString(), Utils.StrToInt(field2.MaxValue, 50));
                            }
                            else if (field2.FieldType == 10)
                            {
                                row[field2.FieldName] = Utils.cutTrueLength(row[field2.FieldName].ToString(), 300);
                            }
                            else if (field2.FieldType == 11)
                            {
                                row[field2.FieldName] = Utils.cutTrueLength(row[field2.FieldName].ToString(), 0x5dc);
                            }
                            else
                            {
                                row[field2.FieldName] = row[field2.FieldName].ToString();
                            }
                        }
                        else if (GetFieldType(field2.FieldType) == typeof(int))
                        {
                            row[field2.FieldName] = Utils.StrToInt(row[field2.FieldName].ToString(), 0);
                        }
                        else if (GetFieldType(field2.FieldType) == typeof(DateTime))
                        {
                            try
                            {
                                row[field2.FieldName] = DateTime.Parse(row[field2.FieldName].ToString());
                            }
                            catch (Exception exception2)
                            {
                                exception = exception2;
                                row[field2.FieldName] = DateTime.Now;
                            }
                        }
                    }
                }
            }
            row["Title"] = Utils.RemoveHtml(row["Title"].ToString());
            row["Title"] = Utils.cutTrueLength(row["Title"].ToString(), 200);
            row["Summary"] = Utils.RemoveHtml(row["Summary"].ToString());
            row["Summary"] = CmsCatchHack.GetContentSummary(row["Title"].ToString(), row["Summary"].ToString(), row["Content"].ToString());
            row["Summary"] = Utils.cutTrueLength(row["Summary"].ToString(), 400);
            row["Keyword"] = SegmentHelper.GetKeyword(row["Title"].ToString());
            row["Keyword"] = Utils.cutTrueLength(row["Keyword"].ToString(), 100);
            this.dtResutlData.Rows.Add(row);
            return this.dtResutlData;
        }

        public int CatchContent(int nodeID, string catchContent)
        {
            DataRow row;
            Exception exception;
            Publish publish;
            int prevID;
            int nextID;
            int num = -994;
            try
            {
                row = this.Catch(nodeID, catchContent).Rows[0];
            }
            catch (Exception exception1)
            {
                exception = exception1;
                return -995;
            }
            KeRui.Model.CmsContent model = new KeRui.Model.CmsContent();
            KeRui.BLL.CmsContent content2 = new KeRui.BLL.CmsContent();
            KeRui.BLL.CmsNode node = new KeRui.BLL.CmsNode();
            int contentID = Convert.ToInt32(row["ContentID"]);
            if (contentID > 0)
            {
                string str = content2.GetModelDetailsByContentID(Convert.ToInt32(row["ContentID"])).Tables[0].Rows[0]["Content"].ToString();
                try
                {
                    content2.AppendContent(contentID, Utils.SqlStringFormat(str + "<div style=\"page-break-after:always\"><span style=\"display: none\">&nbsp;</span></div>" + row["Content"].ToString()));
                }
                catch (Exception exception2)
                {
                    exception = exception2;
                }
                if (Convert.ToInt32(row["PublicState"]) == 1)
                {
                    try
                    {
                        publish = new Publish();
                        publish.PublishContent(contentID);
                        prevID = content2.GetModel(contentID).PrevID;
                        nextID = content2.GetModel(contentID).NextID;
                        if (prevID != 0)
                        {
                            publish.PublishContent(prevID);
                        }
                        if (nextID != 0)
                        {
                            publish.PublishContent(nextID);
                        }
                    }
                    catch (Exception exception3)
                    {
                        exception = exception3;
                    }
                }
                return contentID;
            }
            KeRui.Model.CmsNode modelByCache = node.GetModelByCache(nodeID);
            model.NodeID = Convert.ToInt32(row["NodeID"]);
            model.Title = row["Title"].ToString();
            model.Summary = row["Summary"].ToString();
            model.PublicState = Convert.ToInt32(row["PublicState"]);
            model.ContentState = Convert.ToInt32(row["ContentState"]);
            model.ContentType = Convert.ToInt32(row["ContentType"]);
            model.PublishTime = DateTime.Parse(row["PublishTime"].ToString());
            model.TitleStyle = "";
            model.UserID = 1;
            model.IsRecommend = Convert.ToInt32(row["IsRecommend"]) == 1;
            model.IsHot = Convert.ToInt32(row["IsHot"]) == 1;
            model.IsTop = Convert.ToInt32(row["IsTop"]) == 1;
            model.IsMarked = Convert.ToInt32(row["IsMarked"]) == 1;
            model.EnableComment = false;
            model.TemplateFile = modelByCache.ContentDefaultTemplateFile.Substring(modelByCache.ContentDefaultTemplateFile.LastIndexOf('\\')).Remove(0, 1);
            model.FileDir = "";
            model.FilePath = "";
            model.PublicStartTime = DateTime.Parse("1900-1-1");
            model.PublicEndTime = DateTime.Parse("1900-1-1");
            model.CreateIP = "127.0.0.1";
            model.PicUrl = row["PicUrl"].ToString();
            try
            {
                num = content2.Add(model);
            }
            catch (Exception exception4)
            {
                exception = exception4;
                Utils.ErrorNote("数据库", "添加至内容基础数据出错，详情：" + exception.Message + "\r\n\r\n");
                return -992;
            }
            StringBuilder builder = new StringBuilder();
            int modelID = modelByCache.ModelID;
            builder.AppendFormat("INSERT INTO CmsContent{0} (", modelID);
            builder.Append("[ContentID],[Title],");
            StringBuilder builder2 = new StringBuilder();
            builder2.AppendFormat("{0},", num);
            builder2.AppendFormat("'{0}',", Utils.SqlStringFormat(row["Title"].ToString()));
            KeRui.BLL.CmsField field = new KeRui.BLL.CmsField();
            List<KeRui.Model.CmsField> listByCache = new List<KeRui.Model.CmsField>();
            try
            {
                listByCache = field.GetListByCache("ModelID=" + modelID + " AND IsUsing='True' AND FieldName NOT IN('Title','ContentID')");
            }
            catch (Exception exception5)
            {
                exception = exception5;
                Utils.ErrorNote("数据库", string.Concat(new object[] { "添加至内容个性数据前获取Field出错，删除ContentID：", num, "，详情：", exception.Message, "\r\n\r\n" }));
                try
                {
                    Common.ExecuteSQL("delete cmscontent where contentid=" + num);
                }
                catch
                {
                }
            }
            for (int i = 0; i < listByCache.Count; i++)
            {
                if (i != (listByCache.Count - 1))
                {
                    builder.AppendFormat("[{0}],", listByCache[i].FieldName);
                    if (listByCache[i].FieldType == 8)
                    {
                        builder2.Append(row[listByCache[i].FieldName.ToLower()] + ",");
                    }
                    else
                    {
                        builder2.Append("'" + Utils.SqlStringFormat(row[listByCache[i].FieldName.ToLower()].ToString()) + "',");
                    }
                }
                else
                {
                    builder.AppendFormat("[{0}]", listByCache[i].FieldName);
                    if (listByCache[i].FieldType == 8)
                    {
                        builder2.Append(row[listByCache[i].FieldName.ToLower()] + ",");
                    }
                    else
                    {
                        builder2.Append("'" + Utils.SqlStringFormat(row[listByCache[i].FieldName.ToLower()].ToString()) + "'");
                    }
                }
            }
            builder.Append(") VALUES (");
            builder.Append(builder2);
            builder.Append(")");
            try
            {
                Common.ExecuteSQL(builder.ToString());
            }
            catch (Exception exception6)
            {
                exception = exception6;
                try
                {
                    Common.ExecuteSQL("delete cmscontent where contentid=" + num);
                }
                catch
                {
                }
                Utils.ErrorNote("ExecuteSQL", string.Concat(new object[] { "Web:\r\n", catchContent, "\r\nSql:\r\n", builder.ToString(), "\r\n错误，删除ContentID：", num, "，详情：", exception.Message, "\r\n\r\n" }));
                return -990;
            }
            if (Convert.ToInt32(row["PublicState"]) == 1)
            {
                try
                {
                    publish = new Publish();
                    publish.PublishContent(num);
                    prevID = content2.GetModel(num).PrevID;
                    nextID = content2.GetModel(num).NextID;
                    if (prevID != 0)
                    {
                        publish.PublishContent(prevID);
                    }
                    if (nextID != 0)
                    {
                        publish.PublishContent(nextID);
                    }
                }
                catch (Exception exception7)
                {
                    exception = exception7;
                }
            }
            return num;
        }

        private static Type GetFieldType(int fieldType)
        {
            switch (fieldType)
            {
                case 1:
                case 2:
                case 3:
                case 7:
                case 10:
                    return typeof(string);

                case 8:
                    return typeof(int);

                case 9:
                    return typeof(DateTime);
            }
            return typeof(string);
        }
    }
}

